package com.shy.db.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.shy.api.model.PaymentApiData;
import com.shy.api.model.dto.KqNoticeResultDto;
import com.shy.api.model.dto.NoticeResultDto;
import com.shy.api.model.enums.TradeStatusEnum;
import com.shy.api.model.query.*;
import com.shy.db.entity.TradeOrder;
import com.shy.db.entity.UserPayConfig;
import com.shy.db.entity.UserPayInfo;
import com.shy.db.mapper.TradeOrderMapper;
import com.shy.db.mapper.UserPayConfigMapper;
import com.shy.db.mapper.UserPayInfoMapper;
import com.shy.db.service.ThirdPartApiService;
import com.shy.mq.MessageNotice;
import com.shy.mq.service.RabbitMessageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;


//使用支付方式wayCode名称作为对象名称（Bean id）
@Service("KUAIQIAN")
public class KQThirdPartApiServiceImpl implements ThirdPartApiService {
    @Resource
    private UserPayConfigMapper payConfigMapper;

    @Resource
    private UserPayInfoMapper payInfoMapper;

    @Resource
    private TradeOrderMapper tradeOrderMapper;
    @Resource
    private RabbitMessageService rabbitMessageService;


    @Override
    public PaymentApiData invokePaymentApi(MerchTradeQuery tradeQuery) {
        //获取ip
        QueryWrapper<UserPayConfig> configWrapper = new QueryWrapper<>();
        configWrapper.eq("user_no", tradeQuery.getUserNo())
                .eq("product_code", tradeQuery.getPayProductCode());
        UserPayConfig userPayConfig = payConfigMapper.selectOne(configWrapper);

        //商家的服务器ip地址，逗号分割的多个，取一个
        String merchantServerIp = userPayConfig.getMerchantServerIp();
        String ip = merchantServerIp.split(",")[0];

        //获取快钱第三方支付配置
        QueryWrapper<UserPayInfo> payInfoWrapper = new QueryWrapper<>();
        payInfoWrapper.eq("user_no", tradeQuery.getUserNo())
                .eq("product_code", tradeQuery.getPayProductCode())
                .eq("pay_way_code", tradeQuery.getWayCode());
        UserPayInfo userPayInfo = payInfoMapper.selectOne(payInfoWrapper);
        JSONObject json = JSONUtil.parseObj(userPayInfo.getPayConfig());

        KuaiQianGatewayData gatewayData = new KuaiQianGatewayData();
        gatewayData.setMerchantAcctId(json.getStr("merchId"));
        gatewayData.setMerchIp(ip);
        gatewayData.setShopName(userPayConfig.getShopName());
        gatewayData.setOrderId("GKQ" + IdWorker.getId());
        gatewayData.setPrivateKey(json.getStr("privateFile"));
        gatewayData.setPublicKey(json.getStr("publicFile"));
        gatewayData.setAccessCode(json.getStr("accessCode"));
        gatewayData.setAccessAlias(json.getStr("alias"));
        //创建快钱支付需要的接口参数
        PaymentApiData paymentApiData = new KuaiQianPaymentApiData(gatewayData, tradeQuery);

        //记录支付记录
        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setId("7" + IdWorker.getId());
        tradeOrder.setUserNo(tradeQuery.getUserNo());
        tradeOrder.setUserName(userPayConfig.getShopName());
        tradeOrder.setUserOrderNo(tradeQuery.getOrderNo());
        tradeOrder.setTxNo(gatewayData.getOrderId());
        tradeOrder.setOrderAmount(new BigDecimal(tradeQuery.getOrderMoney()));
        tradeOrder.setOrderTime(new Date());
        tradeOrder.setPayProductCode(tradeQuery.getPayProductCode());
        tradeOrder.setPayWayCode(tradeQuery.getWayCode());
        tradeOrder.setPayWayName("快钱");
        tradeOrder.setPayTypeCode("PC_PAY");
        tradeOrder.setPayTypeName("网银支付");
        tradeOrder.setPageurl(tradeQuery.getPageUrl());
        tradeOrder.setNotifyurl(tradeQuery.getNotifyUrl());
        tradeOrder.setRemark("创建快钱的支付");
        tradeOrder.setEditTime(new Date());
        tradeOrder.setStatus(TradeStatusEnum.CREATE.name());
        tradeOrderMapper.insert(tradeOrder);

        return paymentApiData;
    }

    @Override
    public NoticeResultDto handleNotice(NoticeQuery noticeQuery) {
        //查询订单
        KqNoticeQuery noticeData = (KqNoticeQuery) noticeQuery;

        QueryWrapper<TradeOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("tx_no", noticeData.getOrderId());
        TradeOrder tradeOrder = tradeOrderMapper.selectOne(wrapper);
        if (tradeOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!Objects.equals(tradeOrder.getStatus(), TradeStatusEnum.CREATE.name())) {
            throw new RuntimeException("订单已处理");
        }
        if ("10".equals(noticeData.getPayResult())) {
            //处理成功,修改订单状态为成功
            tradeOrderMapper.updateStatus(tradeOrder.getId(), TradeStatusEnum.SUCCESS.name());
        } else {
            //处理失败,修改订单状态为失败
            tradeOrderMapper.updateStatus(tradeOrder.getId(), TradeStatusEnum.FAILURE.name());
        }
        KqNoticeResultDto resultDto = new KqNoticeResultDto();
        resultDto.setPageUrl(tradeOrder.getPageurl());

        // 将支付结果信息放到Rabbit
        MessageNotice messageNotice = new MessageNotice();
        messageNotice.setUserNo(tradeOrder.getUserNo());
        messageNotice.setOrderNo(tradeOrder.getUserOrderNo());
        messageNotice.setTxNo(tradeOrder.getTxNo());
        messageNotice.setOrderAmount(tradeOrder.getOrderAmount().toPlainString());
        messageNotice.setPayResult("10".equals(noticeData.getPayResult()) ? "SUCCESS" : "FAILURE");
        messageNotice.setPayWayCode(tradeOrder.getPayWayCode());
        messageNotice.setNotifyUrl(tradeOrder.getNotifyurl());
        messageNotice.setLastDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        messageNotice.setNoticeTimes(0);
        messageNotice.setMaxNoticeTimes(3);

        rabbitMessageService.sendNoticeMessage(messageNotice);

        return resultDto;
    }
}
